/*
 * @Description:
 * @Autor: GuluGuluu
 * @Date: 2023-06-24 14:24:54
 * @LastEditors: GuluGuluu
 * @LastEditTime: 2023-06-26 17:11:33
 */
import React, { useState } from "react";
import MyModal from "../components/MyModal";
const ModalContext = React.createContext(undefined);

export const ModalProvider = ({ children }) => {
  const [visible, setVisible] = useState(false);
  const [content, setContent] = useState("");
  const [handleOk, setHandleOk] = useState(null);
  const [title, setTitle] = useState("提示");
  const [loading, setLoading] = useState(false);
  const [okType, setOkType] = useState("primary");

  const open = ({ content, title = "提示", handleOk, okType = "primary" }) => {
    setContent(content);
    setHandleOk(async () => {
      await handleOk();
      handleCancel();
    });
    setVisible(true);
    setOkType(okType);
    setTitle(title);
  };
  const handleCancel = () => {
    setVisible(false);
    setHandleOk(null);
  };
  return (
    <ModalContext.Provider
      children={
        <>
          <MyModal
            content={content}
            handleOk={handleOk}
            title={title}
            visible={visible}
            loading={loading}
            okType={okType}
            handleCancel={handleCancel}
          />
          {children}
        </>
      }
      value={{ open }}
    />
  );
};

export const useModal = () => {
  const context = React.useContext(ModalContext);
  if (!context) {
    throw new Error("useModal必须在ModalProvider中使用");
  }
  return context;
};
